const express = require("express");
const router = express.Router();
const config = require("../mod/config");
const request = require("../mod/request");
const map = require("../mod/map").map;
/*
 *名称：产品详情
 *描述：
 */
router.get("/:shopId/p:id", (req, res) => {
   var shopId = req.params.shopId;
   var pid = req.params.id;
    // console.log(productId);
  request.send({path : "/tripday/product/detail/"+pid+"?b2bUserId="+shopId  , clientReq :  req, callback :  function(data){
    if(data.code == 1){
      var obj = data.result;
      if(obj&&obj.productInfo!=undefined){
        obj.conf = config;
        obj.shopId = shopId;
        obj.picUrl = config.pic;
        res.render("product/detail", obj);
      }else{
        next();
      }
    }else if(data.code == 3){
      res.render('unsale',{
        staticServer: config.staticServer,
        conf:config
      })
    }else{
      res.status(404).render("error");
    }
  },function(status){
    if(status != 200){
      res.status(404).render("error");
    }
  }});

});
/*
 *名称：产品搜索结果
 *描述：拦截产品列表路由返回产品列表页视图
 */
router.get("/:shopId/searchList",function(req, res, next){
  var 
    shopId = req.params.shopId;
    res.render('product/search',{
      conf:config,
      shopId:shopId
    })
});
/*
 *名称：产品列表页
 *作者：roway.luo@aoliday.com
 *描述：拦截产品列表路由，根据groupid、zoneId、countryId请求产品列表，返回产品列表页视图
 */
router.get("/:shopId/g:groupId/z:zoneId/t:tagCode",function(req, res, next){
  var tagCode = req.params.tagCode,
    groupId = req.params.groupId,
    zone = req.params.zoneId,
    zoneId = zone.split("p")[0],
    plateId = zone.split("p")[1],
    shopId = req.params.shopId;
  renderProductList(req,res,shopId,"",tagCode,groupId,"",zoneId,plateId);
});

/*
 *名称：产品列表页
 *作者：roway.luo@aoliday.com
 *描述：拦截产品列表路由，根据groupid、zoneId、countryId请求产品列表，返回产品列表页视图
 */
router.get("/:shopId/g:groupId/v:countryId/c:cityId",function(req, res, next){
  var countryId = req.params.countryId,
    groupId = req.params.groupId,
    zoneId = "",
    plateId = "",
    cityId = req.params.cityId,
    shopId = req.params.shopId;
  renderProductList(req,res,shopId,cityId,"",groupId,countryId,zoneId,plateId);
});
/*
 *名称：产品列表页
 *作者：roway.luo@aoliday.com
 *描述：拦截产品列表路由，根据groupid、zoneId、countryId请求产品列表，返回产品列表页视图
 */
router.get("/:shopId/g:groupId/z:zoneId/v:countryId",function(req, res, next){
  var countryId = req.params.countryId,
    groupId = req.params.groupId,
    zone = req.params.zoneId,
    zoneId = zone.split("p")[0],
    plateId = zone.split("p")[1],
    shopId = req.params.shopId;
  renderProductList(req,res,shopId,"","",groupId,countryId,zoneId,plateId);
});
/*
 *名称：产品列表页
 *作者：roway.luo@aoliday.com
 *描述：拦截产品列表路由，根据groupid、zoneId、countryId、cityid请求产品列表，返回产品列表页视图
 */
router.get("/:shopId/g:groupId/z:zoneId/v:countryId/c:cityId",function(req, res, next){
  var cityId = req.params.cityId,
    groupId = req.params.groupId,
    zone = req.params.zoneId,
    zoneId = zone.split("p")[0],
    plateId = zone.split("p")[1],
    countryId = req.params.countryId,
    shopId = req.params.shopId;
  renderProductList(req,res,shopId,cityId,"",groupId,countryId,zoneId,plateId);
});
/*
 *名称：产品列表页
 *作者：roway.luo@aoliday.com
 *描述：拦截产品列表路由，根据groupid、zoneId、countryId、tagCode筛选标签请求产品列表，返回产品列表页视图
 */
router.get("/:shopId/g:groupId/z:zoneId/v:countryId/t:tagCode",function(req, res, next){
  var tagCode = req.params.tagCode,
    groupId = req.params.groupId,
    zone = req.params.zoneId,
    zoneId = zone.split("p")[0],
    plateId = zone.split("p")[1],
    countryId = req.params.countryId,
    shopId = req.params.shopId;
  renderProductList(req,res,shopId,"",tagCode,groupId,countryId,zoneId,plateId);
});
/*
 *名称：产品列表页
 *作者：roway.luo@aoliday.com
 *描述：拦截产品列表路由，根据groupid、zoneId、tagCode筛选标签请求产品列表，返回产品列表页视图
 */
router.get("/:shopId/g:groupId/z:zoneId/v:countryId/c:cityId/t:tagCode",function(req, res, next){
  var tagCode = req.params.tagCode,
    groupId = req.params.groupId,
    zone = req.params.zoneId,
    zoneId = zone.split("p")[0],
    plateId = zone.split("p")[1],
    countryId = req.params.countryId,
    cityId = req.params.cityId,
    shopId = req.params.shopId;
  renderProductList(req,res,shopId,cityId,tagCode,groupId,countryId,zoneId,plateId);
});
/*
 *名称：查询产品列表和筛选条件
 *作者：adam.li@aoliday.com
 *描述：使用eventproxy模块处理并发请求
 */
function renderProductList(req,response,shopid,cityId,tagCode,groupId,countryId,zoneId,plateId){
  try{
    var groups = map.group,
      citys = map.city,
      plates = map.plate,
      zoneId = zoneId || "",
      plateId = plateId || "",
      countryId = countryId || "",
      cityId = cityId || "",
      tags = tagCode ? tagCode.substring(2) : "",
      tagId = getTags(tags),
      tagIds = tagCode ? tags.replace(/-/g,";").replace(/d/g,",") : "",
      groupId = groupId || (tagCode?groups[tagCode.split("-")[0]].id:100),
      tagName = plates[groupId]||"自助游",
      title = "",
      data = {
        pageSize:10,
        pageStart:1,
        tagIds:tagId.tagIds||"",
        tagGroupIds:tagId.tagGroupIds||"",
        groupId:groupId,
        cityId:cityId||""
      };
    //未改变标签是通过d来进行同组标签分割，现在全部传值为组groupId
    if(tagCode.indexOf("d") > -1){
      response.redirect("/g"+groupId+"/z"+zoneId+"p"+plateId);
      return false;
    }
    // ep.all('product_list', 'tag_group' , 'country', function (obj1, obj2 , obj3) {
    //   var isJson = (obj1&&obj1.total!=undefined)&&(obj2);
    //   if(isJson){
    //     response.render("product/list", {
    //       title : title,
    //       shopId : shopid,
    //       tagName : tagName,
    //       zone : obj3 || [],
    //       areaName : getAreaName(obj3 , zoneId , countryId , cityId),
    //       zoneId : zoneId,
    //       plateId : plateId,
    //       countryId : countryId,
    //       groupId : groupId||"",
    //       cityId : cityId||"",
    //       tagIds : tagIds||"",
    //       tagId : data.tagIds,
    //       tagGroupIds : data.tagGroupIds,
    //       conf:config,
    //       otherGroup : obj2.otherGroup,
    //       productList : obj1.datas||[],
    //       total : obj1.total
    //     });
    //   }else{
    //     response.status(404).render("error");
    //   }
    // });
    request.all(
      [
      //产品列表
      { path: "/tripday/product/list?b2bUserId="+shopid+"&pageSize=10&pageStart=0&shopId=9&plateId="+plateId+"&zoneId="+zoneId+"&countryIds="
      +countryId+"&tagIds="+data.tagIds+"&tagGroupIds="+data.tagGroupIds+"&groupId="+data.groupId+"&cityId="+data.cityId, clientReq: req },
      //推荐产品
      {path: "/tripday/product/recommendProductList?b2bUserId="+shopid, clientReq: req},
      //城市       
      { path: "/pc/queryCountryCity?b2bUserId="+shopid, clientReq: req },
      //标签
      { path: "/tripday/product/queryTagGroup?b2bUserId="+shopid+"&zoneId="+zoneId+"&countryIds="+countryId+"&groupId="+data.groupId+"&cityIds="+data.cityId, clientReq: req },

      ],
      (_data) => {
       if(_data[0] && _data[0].result ){
        response.render("product/list", {
          conf:config,
          shopId : shopid,
          title : title,
          recommendProduct:_data[1] && _data[1].result || [],//推荐
          productList : _data[0].result.datas ||[],
          total : _data[0].result.total,
          countryId: countryId,
          cityId : cityId||"",
          groupId:groupId,
          zoneId : zoneId,
          plateId : plateId,
          tagIds : tagIds||"",
          tagId : data.tagIds,
          tagGroupIds : data.tagGroupIds,
          otherGroup : _data[3].result.otherGroup || {},
          citys:  _data[2] && _data[2].result  && _data[2].result[countryId]  || []
        });
      }else{
        response.render("404", {
          conf:conf
        });
      }
    },
    (error) => {
      response.render("404", {
        conf:conf
      });
    }
    );
  }catch(e){
    console.log('\r\n', e, '\r\n', e.stack);
    try {
      response.end(e.stack);
    } catch(e) { }
  }
}
function getAreaName(data , zoneId , countryId , cityId){
  var areaName = "";
  for(var i = 0 ; i < data.length ; i++){
    var zone = data[i];
    if(countryId != ""){
      for(var j = 0 ; j < zone.regions.length ; j++){
        var country = zone.regions[j];
        if(cityId != ""){
          for(var n = 0 ; n < country.cities.length ; n++){
            var city = country.cities[n];
            if(city.cityId == cityId){
              areaName = city.cityName;
              break;
            }
          }
        }else{
          if(country.countryId == countryId){
            areaName = country.name;
            break;
          }
        }
      }
    }else{
      if(zone.zone.zoneId == zoneId){
        areaName = zone.name ;
        break;
      }
    }
  }
  return areaName;
}
function getTags(string){
  var tagIds = [];
  var tagGroupIds = [];
  var tags = string.split("-");
  for(var i = 0 ; i < tags.length ; i++){
    var code = tags[i];
    if(code.indexOf("g") > -1){
      tagGroupIds.push(code.replace(/g/,""));
    }else{
      tagIds.push(code);
    }
  }
  return {
    tagIds : tagIds.join(";"),
    tagGroupIds : tagGroupIds.join(";")
  }
}
module.exports = router;